export function get (key, defaultValue) {
  var string = getString(key)
  if (!string) {
    return defaultValue
  }
  return JSON.parse(string)
}

export function getString (key, defaultValue) {
  var string = localStorage.getItem(key)
  if (!string) {
    string = defaultValue
  }
  return string
}

export function set (key, val) {
  localStorage.setItem(key, typeof val === 'object' ? JSON.stringify(val) : val)
  return val
}

export function put (key, o) {
  var val = get(key)
  if (val) {
    return set(key, Object.assign(val, o))
  }
  return set(key, o)
}

export function remove (key) {
  localStorage.removeItem(key)
}

export function id () {
  // return Math.random().toString(36).substr(2, 16)
  return Math.floor((1 + Math.random()) * 0x10000).toString(16)
}

export function getCookie (name, json) {
  var cookies = document.cookie.split('; ')
  for (var i = 0; i < cookies.length; i++) {
    var arr = cookies[i].split('=')
    if (arr[0] == name) {
      var value = decodeURIComponent(arr[1])
      return json ? JSON.parse(value) : value
    }
  }
  return ''
}

export function setCookie (name, value, days) {
  var expires = ''
  if (days) {
    var date = new Date()
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000))
    expires = '; expires=' + date.toUTCString()
  }
  document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value || '') + expires + '; path=/'
}

export function removeCookie (name) {
  document.cookie = name + '=; Max-Age=-1;'
}
